# -*- coding:utf-8 -*-
import sys
import cv2
import os
import numpy as np
from math import *
import threading


global flag_find_paper 
global flag_move 

flag_find_paper =0
flag_move  = 0
# def nothing(x):  # 滑动条的回调函数
#     pass

# WindowName_ball = 'Trackbar'  # 窗口名
# cv2.namedWindow(WindowName_ball, cv2.WINDOW_AUTOSIZE)  # 建立空窗口
# cv2.createTrackbar('h_low', WindowName_ball, 0, 10, nothing)  # 创建滑动条
# cv2.createTrackbar('h_high', WindowName_ball, 160,200, nothing)  # 创建滑动条
# cv2.createTrackbar('s_low', WindowName_ball, 0, 20, nothing)  # 创建滑动条
# cv2.createTrackbar('s_high', WindowName_ball, 21, 255, nothing)  # 创建滑动条
# cv2.createTrackbar('v_low', WindowName_ball, 0, 221, nothing)  # 创建滑动条
# cv2.createTrackbar('kernel', WindowName_ball, 7, 50, nothing)  # 创建滑动条
# cv2.createTrackbar('iterations', WindowName_ball, 2, 20, nothing)  # 创建滑动条

# baise:  h : 0-180   s :  0-30  v : 221-225



def get_paper(frame):
    global flag_find_paper  
    aero = 0
    gs_frame = cv2.GaussianBlur(frame, (5, 5), 0)                     # 高斯模糊
    hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV)                 # 转化成HSV图像

    color_dist = {'white': {'Lower': np.array([1, 1, 22]), 'Upper': np.array([200, 50, 255])},
                }

    erode_hsv = cv2.erode(hsv,np.ones((15, 15), np.uint8), iterations=2)                   # 腐蚀 粗的变细
    inRange_hsv_g = cv2.inRange(erode_hsv, color_dist['white']['Lower'], color_dist['white']['Upper'])
    cnts_w = cv2.findContours(inRange_hsv_g.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]    #找轮廓
    cv2.imshow("inRange_hsv", inRange_hsv_g)
    if len(cnts_w)!=0:
        c_w = max(cnts_w, key=cv2.contourArea)   #找最大面积轮廓
        rect_w = cv2.minAreaRect(c_w)     #最小外接矩形框
        box_w = cv2.boxPoints(rect_w)     #矩形框四点坐标
        cv2.drawContours(frame, [np.int0(box_w)], -1, (0, 255, 0), 2)     #画框
        aero = cv2.contourArea(c_w )   #得到轮廓面积
        # print(aero)
        if aero >50000 and flag_find_paper == 0:    #白色面积足够大（具体数值届时再算） 而且  上一状态是没有找到白纸  而且  现在魔方静止  
            print('find  paper     find  paper    find  paper   find  paper  ')
            print(aero)
            flag_find_paper = 1
            return False
        if aero < 20000 and flag_find_paper == 1:   #白色面积小（具体数值届时再算） 而且  上一状态是已经找到白纸  而且  现在魔方静止  
            print('move    move    move   move move    move    move   move ')
            print(aero)
            flag_find_paper = 0
            return True
        return False
    elif flag_find_paper == 1:   #如果没有轮廓
        print('move    move    move   move move    move    move   move ')
        flag_find_paper = 0
        return True


if __name__ == '__main__':
    # main()中主要做了模板匹配的操作，模板相减得到污染物位置没有做
    
    cap = cv2.VideoCapture(1)
    # cap.set(3, 1280)
    # cap.set(4, 1024)
    while True:
        secuess, fream1 = cap.read()
        fream1 = fream1[145:450, 170:550]
        cv2.imshow('ss',fream1)
        if not secuess:
            print("false in reading cam")
            break
        get_paper(fream1)
        key = cv2.waitKey(10)
        if key == 27:
            break
    
